/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.emergency.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.util.DocConverterUtils;
import com.koron.emergency.domain.DrillAssessment;
import com.koron.emergency.mapper.DrillAssessmentMapper;
import com.koron.emergency.service.api.DrillAssessmentService;
import com.koron.emergency.util.BusinessCode;
import com.koron.workflow.bean.MessageEntity;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.util.*;

@Service
public class DrillAssessmentServiceImpl implements DrillAssessmentService {
    private final static  Logger logger = LoggerFactory.getLogger(DrillAssessmentServiceImpl.class);
    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Override
    public MessageBean<Integer> save(DrillAssessment bean, MultipartFile[] files, String keepAddress, String delAddress, String pdfKeepFiles, String pdfDelFiles) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", Integer.class);
        List<String> keepList = new ArrayList<>();
        List<String> pdfKeepList = new ArrayList<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(bean.getName())) {
                msg.setCode(BusinessCode.DRILLASSESSMENT_EMPTY_NAME.getCode());
                msg.setDescription(BusinessCode.DRILLASSESSMENT_EMPTY_NAME.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getCorpCode())) {
                msg.setCode(BusinessCode.DRILLASSESSMENT_EMPTY_CORPCODE.getCode());
                msg.setDescription(BusinessCode.DRILLASSESSMENT_EMPTY_CORPCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getPurpose())) {
                msg.setCode(BusinessCode.DRILLASSESSMENT_EMPTY_PURPOSE.getCode());
                msg.setDescription(BusinessCode.DRILLASSESSMENT_EMPTY_PURPOSE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getManager())) {
                msg.setCode(BusinessCode.DRILLASSESSMENT_EMPTY_MANAGER.getCode());
                msg.setDescription(BusinessCode.DRILLASSESSMENT_EMPTY_MANAGER.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getPlace())) {
                msg.setCode(BusinessCode.DRILLASSESSMENT_EMPTY_PLACE.getCode());
                msg.setDescription(BusinessCode.DRILLASSESSMENT_EMPTY_PLACE.getDescription());
                return msg;
            }
            if (null == bean.getDrillMethod() || (bean.getDrillMethod() != 0 && bean.getDrillMethod() != 1 && bean.getDrillMethod() != 2)) {
                msg.setCode(BusinessCode.DRILLASSESSMENT_EMPTY_METHOD.getCode());
                msg.setDescription(BusinessCode.DRILLASSESSMENT_EMPTY_METHOD.getDescription());
                return msg;
            }
            if (null == bean.getDrillTime()) {
                msg.setCode(BusinessCode.DRILLASSESSMENT_EMPTY_TIME.getCode());
                msg.setDescription(BusinessCode.DRILLASSESSMENT_EMPTY_TIME.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getSponsorDeptCode()) || StringUtils.isEmpty(bean.getSponsorDeptName())) {
                msg.setCode(BusinessCode.DRILLASSESSMENT_EMPTY_SPONSORDEPTCODE.getCode());
                msg.setDescription(BusinessCode.DRILLASSESSMENT_EMPTY_SPONSORDEPTCODE.getDescription());
                return msg;
            }
            if (null == bean.getContingencyPlanId()) {
                msg.setCode(BusinessCode.DRILLASSESSMENT_EMPTY_CONTINGENCYPLANID.getCode());
                msg.setDescription(BusinessCode.DRILLASSESSMENT_EMPTY_CONTINGENCYPLANID.getDescription());
                return msg;
            }
            Integer count = factory.getMapper(DrillAssessmentMapper.class).doubleName(bean.getCorpCode(), bean.getName(), bean.getId());
            if (count > 0) {
                msg.setCode(BusinessCode.DRILLPLAN_DOUBLE_NAME.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_DOUBLE_NAME.getDescription());
                return msg;
            }
            if (null != files && files.length > 0) {
                for (MultipartFile file : files) {
                    String url = clientWrapper.uploadFile(file);
                    keepList.add(url + "#" + file.getOriginalFilename());
                    String pdfUrl = docConverterUtils.converterUpdate(file);
                    pdfKeepList.add(StringUtils.isEmpty(pdfUrl) ? null : pdfUrl);
                }
            }
            Integer value = 0;
            if (StringUtils.isEmpty(bean.getId())) {
                //新增
                bean.setAddTime(bean.getUpdateTime());
                bean.setAddUser(bean.getUpdateUser());
                bean.setAddUserName(bean.getUpdateUserName());
                bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                if (null != keepList && keepList.size() > 0)
                    bean.setAttachment(new Gson().toJson(keepList));
                if (null != pdfKeepList && pdfKeepList.size() > 0)
                    bean.setPreviewAttachment(new Gson().toJson(pdfKeepList));
                value = factory.getMapper(DrillAssessmentMapper.class).insert(bean);
            } else {
                //修改
                DrillAssessment entity = queryOne(bean.getId()).getData();
                if (null == entity) {
                    msg.setCode(BusinessCode.DRILLPLAN_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.DRILLPLAN_NOT_EXIST.getDescription());
                    return msg;
                }
                if (StringUtils.isNotEmpty(keepAddress)) {
                    String[] keepArray = keepAddress.split("[,，]");
                    for (String keep : keepArray) {
                        keepList.add(keep);
                    }
                }
                if (StringUtils.isNotEmpty(pdfKeepFiles)) {
                    String[] keepArray = pdfKeepFiles.split("[,，]");
                    for (String keep : keepArray) {
                        pdfKeepList.add(keep);
                    }
                }
                if (null != keepList && keepList.size() > 0)
                    bean.setAttachment(new Gson().toJson(keepList));
                if (null != pdfKeepList && pdfKeepList.size() > 0)
                    bean.setPreviewAttachment(new Gson().toJson(pdfKeepList));
                value = factory.getMapper(DrillAssessmentMapper.class).update(bean);
            }
            if (value > 0) {
                if (StringUtils.isNotEmpty(delAddress)) {
                    String[] delArray = delAddress.split("[,，]");
                    for (String keep : delArray) {
                        clientWrapper.deleteFile(keep.split("#")[0]);
                    }
                }
                if (StringUtils.isNotEmpty(pdfDelFiles)) {
                    String[] delArray = pdfDelFiles.split("[,，]");
                    for (String keep : delArray) {
                        clientWrapper.deleteFile(keep.split("#")[0]);
                    }
                }
                msg.setData(value);
                return msg;
            } else {
                if (null != keepList && keepList.size() > 0) {
                    if (StringUtils.isEmpty(keepAddress)) {
                        for (String url : keepList) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    } else {
                        List<String> keeps = Arrays.asList(keepAddress.split("[,，]"));
                        for (String url : keepList) {
                            if (!keeps.contains(url)) {
                                clientWrapper.deleteFile(url.split("#")[0]);
                            }
                        }
                    }
                }
                if (null != pdfKeepList && pdfKeepList.size() > 0) {
                    if (StringUtils.isEmpty(pdfKeepFiles)) {
                        for (String url : pdfKeepList) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    } else {
                        List<String> keeps = Arrays.asList(pdfKeepFiles.split("[,，]"));
                        for (String url : pdfKeepList) {
                            if (!keeps.contains(url)) {
                                clientWrapper.deleteFile(url.split("#")[0]);
                            }
                        }
                    }
                }
                msg.setData(value);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("保存失败");
                return msg;
            }
        } catch (Exception e) {
            if (null != keepList && keepList.size() > 0) {
                if (StringUtils.isEmpty(keepAddress)) {
                    for (String url : keepList) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                } else {
                    List<String> keeps = Arrays.asList(keepAddress.split("[,，]"));
                    for (String url : keepList) {
                        if (!keeps.contains(url)) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
            }
            if (null != pdfKeepList && pdfKeepList.size() > 0) {
                if (StringUtils.isEmpty(pdfKeepFiles)) {
                    for (String url : pdfKeepList) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                } else {
                    List<String> keeps = Arrays.asList(pdfKeepFiles.split("[,，]"));
                    for (String url : pdfKeepList) {
                        if (!keeps.contains(url)) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
            }
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> delete(String id) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "删除成功", Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription(BusinessCode.EXCEPTION.getDescription());
                return msg;
            }
            DrillAssessment entity = queryOne(id).getData();
            if (null == entity) {
                msg.setCode(BusinessCode.DRILLPLAN_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.DRILLPLAN_NOT_EXIST.getDescription());
                return msg;
            }
            Integer value = factory.getMapper(DrillAssessmentMapper.class).delete(id);
            if (value > 0) {
                if (StringUtils.isNotEmpty(entity.getAttachment())) {
                    //删除文件
                    List<String> delFiles = JSONObject.parseArray(entity.getAttachment(), String.class);
                    if (null != delFiles && delFiles.size() > 0) {
                        for (String url : delFiles) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
                if (StringUtils.isNotEmpty(entity.getPreviewAttachment())) {
                    //删除pdf文件
                    List<String> delFiles = JSONObject.parseArray(entity.getPreviewAttachment(), String.class);
                    if (null != delFiles && delFiles.size() > 0) {
                        for (String url : delFiles) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
                msg.setData(value);
                return msg;
            } else {
                msg.setData(value);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DrillAssessment> queryOne(String id) {
        MessageBean<DrillAssessment> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "查询演练评估详情成功", DrillAssessment.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription(BusinessCode.EXCEPTION.getDescription());
                return msg;
            }
            DrillAssessment entity = factory.getMapper(DrillAssessmentMapper.class).queryOne(id);
            msg.setData(entity);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<DrillAssessment>> queryByCondition(String corpCode, String name, String sponsorDeptCode, Integer drillMethod, Date startTime, Date endTime, Integer start, Integer rows) {
        MessageBean<DataBean<DrillAssessment>> msg = new MessageEntity<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<DrillAssessment> list = factory.getMapper(DrillAssessmentMapper.class).queryByCondition(corpCode, name, sponsorDeptCode, drillMethod, startTime, getnowEndTime(endTime), start, rows);
            Integer totalNumber = factory.getMapper(DrillAssessmentMapper.class).countByCondition(corpCode, name, sponsorDeptCode, drillMethod, startTime, getnowEndTime(endTime));
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = (totalNumber > rows) ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<DrillAssessment> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setPageSize(rows);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取演练评估列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    private Date getnowEndTime(Date date) {
        if (null != date) {
            Calendar todayEnd = Calendar.getInstance();
            todayEnd.setTime(date);
            todayEnd.set(Calendar.HOUR_OF_DAY, 23);
            todayEnd.set(Calendar.MINUTE, 59);
            todayEnd.set(Calendar.SECOND, 59);
            todayEnd.set(Calendar.MILLISECOND, 999);
            return todayEnd.getTime();
        } else {
            return null;
        }
    }
}
